import Url from "./entity.js";
//时间间隔函数
export function timeInterval(timesData) {
	//如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
	var dateBegin = timesData; //将-转化为/，使用new Date    
	var dateEnd = new Date(); //获取当前时间   
	var dateDiff = Math.abs(dateEnd.getTime() - dateBegin); //时间差的毫秒数
	var yearDiff = Math.floor(dateDiff / (24 * 3600 * 1000 * 365));
	var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
	var leave1 = dateDiff % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
	var hours = Math.floor(leave1 / (3600 * 1000)) //计算出小时数
	//计算相差分钟数
	var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
	var minutes = Math.floor(leave2 / (60 * 1000)) //计算相差分钟数
	//计算相差秒数
	var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
	var seconds = Math.round(leave3 / 1000);
	var timesString = '';
	if (yearDiff != 0) {
		timesString = yearDiff + '年前';
	} else if (yearDiff == 0 && dayDiff != 0) {
		timesString = dayDiff + '天前';
	} else if (dayDiff == 0 && hours != 0) {
		timesString = hours + '小时前';
	} else if (hours == 0 && minutes != 0) {
		timesString = minutes + '分钟前';
	} else if (minutes == 0 && seconds < 60) {
		timesString = '刚刚';
	}
	return timesString
}


// 日期格式化
export function parseTime(time, pattern) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			time = parseInt(time)
		} else if (typeof time === 'string') {
			time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
		}
		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value]
		}
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}


//获取富文本内的图片url地址
export function getImgSrc(richtext, num = 3) {
	let imgList = [];
	richtext.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
		imgList.push(capture);
	});
	imgList = imgList.slice(0, num)
	return imgList;
}

//获取省份
export function getProvince() {
	return new Promise((resolve, reject) => {
		let historyProvince = uni.getStorageSync("historyProvince");
		console.log('historyProvince=', historyProvince);
		if (historyProvince) {
			console.log('缓存存在');
			if (Date.now() - historyProvince.time > 1000 * 60 * 60) { //1000是1ms,这里是1h
				console.log('重新请求网络地址IP');
				getIP().then(res => {
					resolve(res);
				}).catch(err => {
					reject(err);
				})
			} else {
				console.log('直接走缓存');
				resolve(historyProvince.province);
			}

		} else {
			console.log('第一次网络请求');
			getIP().then(res => {
				resolve(res);
			}).catch(err => {
				reject(err);
			})
		}
	}).catch(err => {}); ///
}

//获取地址IP
function getIP() {
	return new Promise((resolve, reject) => {
		uni.request({
			url: "https://restapi.amap.com/v3/ip?key=be1e85c44ed59d301c7f6161a2bce971",
			success: res => {
				let str = "";
				typeof(res.data.province) == "string" ? str = res.data.province: str = "月球";
				resolve(str);
				let obj = {
					province: str,
					time: Date.now()
				}
				uni.setStorageSync("historyProvince", obj); //放缓存里面
			},
			fail: err => {
				reject(res);
			}
		})
	}).catch(); ///
}

//检验邮箱格式
export function checkMail(mail) {
	return RegExp(/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/)
		.test(mail); //返回一个bool值
}
//校验手机格式
export function checkPhone(phone) {
	return RegExp(/^1[34578]\d{9}$/).test(phone); //.test测试一下嘛
}

export function GetStroage(str) {
	let ans;
	uni.getStorage({
		key: str,
		success: (res) => {
			ans = res.data;
		}
	})
	return ans;
}
//token验证
export function checkToken() { //返回值有问题不能用
	// return new Promise((resolve, reject) => {
	let token = GetStroage("token");
	if (token) {
		uni.request({
			url: Url + "/user/checkToken",
			data: {
				Token: token
			},
			header: {
				'Content-Type': 'application/json'
			},
			method: "GET",
			success: (res) => {
				console.log("请求API接口【/user/checkToken】", res);
				// resolve(res);
			}
		})
	} else {
		// resolve(false);
	}
	// });
}
